// NewItemWindow.xaml.cs
//
// Copyright (c) 2007 Mike Strobel
//
// This source code is subject to the terms of the Microsoft Reciprocal License (Ms-RL).
// For details, see <http://www.opensource.org/licenses/ms-rl.html>.
//
// All other rights reserved.

using System.Windows;

using Supremacy.Tech;

namespace Supremacy.Editor
{
    /// <summary>
    /// Interaction logic for NewItemWindow.xaml
    /// </summary>

    public partial class NewItemWindow : Window
    {
        public NewItemWindow()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(NewItemWindow_Loaded);
        }

        void NewItemWindow_Loaded(object sender, RoutedEventArgs e)
        {
            IdentityText.Focus();
        }

        void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            string id = IdentityText.Text.ToUpperInvariant().Trim();
            string name = NameText.Text.Trim();
            if (id.Length == 0)
            {
                MessageBox.Show(
                    "You must enter an identity.",
                    "Invalid Identity",
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning);
                return;
            }
            if (name.Length == 0)
            {
                MessageBox.Show(
                    "You must enter a name.",
                    "Invalid Name",
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning);
                return;
            }
            if (!EnsureUniqueIdentity(id))
            {
                MessageBox.Show(
                    "An object with the identity " + id + " already exists.",
                    "Identity Conflict",
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning);
                return;
            }
            DialogResult = true;
        }

        private bool EnsureUniqueIdentity(string id)
        {
            foreach (TechObjectDesign design in EditorApp.Current.EditorContext.TechDatabase)
            {
                if (design.Key == id)
                    return false;
            }
            return true;
        }

        public static bool GetNewItem(out string identity, out string name)
        {
            NewItemWindow dialog = new NewItemWindow();
            dialog.Owner = EditorApp.Current.MainWindow;
            dialog.ShowDialog();
            if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
            {
                identity = dialog.IdentityText.Text.ToUpperInvariant().Trim();
                name = dialog.NameText.Text.Trim();
                return true;
            }
            else
            {
                identity = null;
                name = null;
                return false;
            }
        }
    }
}